package com.stu.day16.Demo1;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @author zy
 * @date 2025/2/14 10:25
 */
public class UserDaoImpl implements IUserDao{
    private final static String PATH = "src/com/stu/day16/data/user2.txt";
    private List<User> list = new ArrayList<>();


    public void add1(User user) {
        list.add(user);
        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(PATH))){
            oos.writeObject(list);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void add(User user) {
        //TODO 同时创建ObjectOutputStream和ObjectInputStream会导致文件被覆盖。
        //FileOutputStream会清空文件，使得ObjectInputStream读取时文件已为空，引发异常
        //EOFException当在输入流中读取数据时，未预期地到达流的末尾时，会抛出此异常
        List<User> list = new ArrayList<>();
        File file = new File(PATH);
        if (file.exists() && file.length() > 0) {
            try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) {
                //非空判断有问题
                list = (List<User>) in.readObject();

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if(!list.contains(user)) {
            list.add(user);
        }
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) {
            out.writeObject(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<User> findAll() {
        List<User> userList = new ArrayList<>();
        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))){
            userList = (List<User>) in.readObject();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return userList;
    }

    @Override
    public void delById(Integer id) {
//        for(User user : list){
//            if(Objects.equals(user.getId(), id)){
//                list.remove(user);  // 增强for循环内不能进行修改操作
//            }
//        }
        Iterator<User> iterator = list.iterator();
        while(iterator.hasNext()){
            User user = iterator.next();
            if(user.getId().equals(id)){
                iterator.remove();
            }
        }
        try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(PATH))){
            oos.writeObject(list);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}